package com.wn.servlet.resp;

import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * @author yellow Docter
 * @date 2022 -06-28
 * @desc
 *
 * HttpServletRequest:
 *
 * 01 这个类来自哪里
 *    Tomcat 针对前端发起的HTTP请求，创建一个请求对象！
 *
 * 02 这个类有什么作用 ?
 *    HttpServletRequest封装了请求的数据(请求行/请求头/请求体)
 *
 * 03 获取参数的请求方法:
 *   获取的是单个的提交的数据
 *    request.getParameter("");
 *
 *   获取的是多个提交的数据
 *   request.getParameterValues("fav");
 *
 *   把请求提交的参数封装成一个map
 *   request.getParameterMap();
 *
 */
@WebServlet(urlPatterns = "/req01")
public class Req01Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request, response);
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        username:<input type="text" name="username"> <br>
//        password:<input type="password" name="password"> <br>
        // localhost:8080/day02/req01?username=hello&password=123

//        test01(request);

        Map<String, String[]> map = request.getParameterMap();

        // 把map转成 bean对象
        User user = new User();

        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("user = " + user);

    }

    /**
     * 获取页面提交的数据
     * @param request
     */
    private void test01(HttpServletRequest request) {
        String username = request.getParameter("username");
        System.out.println("username = " + username);
        String password = request.getParameter("password");
        System.out.println("password = " + password);

        String sex = request.getParameter("sex");
        System.out.println("sex = " + sex);

        String[] favs = request.getParameterValues("fav");
        System.out.println(Arrays.toString(favs));


        System.out.println("*********************getParameterMap**********************");
        // map 遍历
        Map<String, String[]> map = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = map.entrySet();

        for (Map.Entry<String, String[]> entry : entries) {
            System.out.println("entry.getKey() = " + entry.getKey());
            System.out.println("entry.getValue() = " + Arrays.toString(entry.getValue()));
        }
    }
}
